package com.example.datastoreutils

import UserPreferences
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

// 创建 DataStore 实例
private val Context.dataStore: DataStore<UserPreferences> by dataStore(
    fileName = "user_preferences.pb",
    serializer = UserPreferencesSerializer
)

class UserPreferencesManager(private val context: Context) {

    // 暴露数据流供观察
    val userPreferencesFlow: Flow<UserPreferences> = context.dataStore.data

    //    val exampleData = runBlocking { context.dataStore.data.first() }
    // 获取特定字段的数据流
    val usernameFlow: Flow<String> = context.dataStore.data
        .map { preferences ->
            preferences.username
        }

    // 保存数据
    suspend fun saveUsername(username: String) {
        context.dataStore.updateData { preferences ->
            preferences.toBuilder()
                .setUsername(username)
                .build()
        }
    }

    // 清除所有数据
    suspend fun clear() {
        context.dataStore.updateData {
            UserPreferences.getDefaultInstance()
        }
    }
}

// 实现序列化器
object UserPreferencesSerializer : androidx.datastore.core.Serializer<UserPreferences> {
    override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()

    override suspend fun readFrom(input: java.io.InputStream): UserPreferences {
        return try {
            UserPreferences.parseFrom(input)
        } catch (e: com.google.protobuf.InvalidProtocolBufferException) {
            throw java.io.IOException("Cannot read proto.", e)
        }
    }

    override suspend fun writeTo(t: UserPreferences, output: java.io.OutputStream) {
        t.writeTo(output)
    }
}
